package com.neusoft.elmboot.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.elmboot.mapper.CartMapper;
import com.neusoft.elmboot.mapper.OrderDetailetMapper;
import com.neusoft.elmboot.mapper.OrdersMapper;
import com.neusoft.elmboot.po.Cart;
import com.neusoft.elmboot.po.OrderDetailet;
import com.neusoft.elmboot.po.Orders;
import com.neusoft.elmboot.service.OrdersService;
import com.neusoft.elmboot.util.CommonUtil;

@Service
public class OrdersServiceImpl implements OrdersService{
	
	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private OrderDetailetMapper orderDetailetMapper;

	/*
	 * 该方法是一个事务提交的方法 ,所以要在方法的前面加入@Transactional注解 
	 * 
	 * 返回值是新生成的订单编号
	 */
	@Override
	@Transactional
	public int createOrders(Orders orders) {
		//1.查询当前用户购物车中,当前商家的商品列表
		Cart cart = new Cart();
		cart.setUserId(orders.getUserId());
		cart.setBusinessId(orders.getBusinessId());
		List<Cart> cartlist  = cartMapper.listCart(cart);
		
		
		//2.创建订单(返回新生成的订单编号)
		orders.setOrderDate(CommonUtil.getCurrentDate());
		ordersMapper.saveOrders(orders);// 生成一条新记录,并将订单编号放在orders对象的orderId属性上
		int orderId = orders.getOrderId(); //获取新的订单编号
		
		//3.批量添加订单明细
		List<OrderDetailet> list = new ArrayList<>();
		for (Cart c : cartlist) {
			OrderDetailet  temp = new OrderDetailet();
			temp.setOrderId(orderId);
			temp.setFoodId(c.getFoodId());
			temp.setQuantity(c.getQuantity());
			list.add(temp);
		}
		orderDetailetMapper.saveOrderDetailetBatch(list);
		
		//4.从购物车中删除相关商品信息
		cartMapper.removeCart(cart);
		
		//5. 返回新生成的订单编号
		return orderId;
	}
	
	@Override
	public Orders getOrdersById(Integer orderId) {
		return ordersMapper.getOrdersById(orderId);
	}
	
	@Override
	public List<Orders> listOrdersByUserId(String userId){
		return ordersMapper.listOrdersByUserId(userId);
	}
}
